import Rating from "../models/rating";
import User from "../schema/user"; // 导入User模型

export const ratingController = {
  // 创建或更新评分
  async createOrUpdateRating(req, res) {
    try {
      const { torrentId } = req.params;
      const { score, comment } = req.body;
      const userId = req.user._id;

      if (score < 1 || score > 5) {
        return res.status(400).json({ error: "评分必须在1-5之间" });
      }

      // 查找是否已有评分记录
      const existingRating = await Rating.findOne({ userId, torrentId });
      
      // 只有新评分才增加魔力值，修改评分不增加
      const isNewRating = !existingRating;
      
      const rating = await Rating.findOneAndUpdate(
        { userId, torrentId },
        { score, comment },
        { upsert: true, new: true }
      );
      
      // 如果是新评分，增加用户魔力值
      if (isNewRating) {
        // 每次评分增加10点魔力值
        const magicPointsEarned = 10;
        
        // 更新用户的魔力值
        await User.findByIdAndUpdate(
          userId,
          { $inc: { bonusPoints: magicPointsEarned } }
        );
        
        // 在返回中包含魔力值奖励信息
        rating._doc.magicPointsEarned = magicPointsEarned;
        
        console.log(`用户 ${userId} 评分获得 ${magicPointsEarned} 点魔力值`);
      }

      res.json(rating);
    } catch (error) {
      console.error("Error creating/updating rating:", error);
      res.status(500).json({ error: "创建/更新评分失败" });
    }
  },

  // 获取种子的所有评分
  async getTorrentRatings(req, res) {
    try {
      const { torrentId } = req.params;
      const ratings = await Rating.find({ torrentId })
        .populate("userId", "username")
        .sort({ createdAt: -1 });
      res.json(ratings);
    } catch (error) {
      console.error("Error getting torrent ratings:", error);
      res.status(500).json({ error: "获取评分失败" });
    }
  },

  // 获取用户的所有评分
  async getUserRatings(req, res) {
    try {
      const { userId } = req.params;
      const ratings = await Rating.find({ userId }).sort({ createdAt: -1 });
      res.json(ratings);
    } catch (error) {
      console.error("Error getting user ratings:", error);
      res.status(500).json({ error: "获取评分失败" });
    }
  },

  // 获取用户对特定种子的评分
  async getUserRatingForTorrent(req, res) {
    try {
      const { torrentId, userId } = req.params;
      const rating = await Rating.findOne({ torrentId, userId });
      if (!rating) {
        return res.status(404).json({ error: "未找到评分" });
      }
      res.json(rating);
    } catch (error) {
      console.error("Error getting user rating for torrent:", error);
      res.status(500).json({ error: "获取评分失败" });
    }
  },

  // 获取种子的评分统计
  async getTorrentRatingStats(req, res) {
    try {
      const { torrentId } = req.params;
      const stats = await Rating.aggregate([
        { $match: { torrentId } },
        {
          $group: {
            _id: null,
            averageRating: { $avg: "$score" },
            ratingCount: { $sum: 1 },
          },
        },
      ]);

      res.json(stats[0] || { averageRating: 0, ratingCount: 0 });
    } catch (error) {
      console.error("Error getting torrent rating stats:", error);
      res.status(500).json({ error: "获取评分统计失败" });
    }
  },

  // 删除评分
  async deleteRating(req, res) {
    try {
      const { ratingId } = req.params;
      const rating = await Rating.findById(ratingId);

      if (!rating) {
        return res.status(404).json({ error: "未找到评分" });
      }

      // 只允许评分作者或管理员删除
      if (
        rating.userId.toString() !== req.user._id.toString() &&
        req.user.role !== "admin"
      ) {
        return res.status(403).json({ error: "没有权限删除此评分" });
      }

      await rating.remove();
      res.json({ message: "评分已删除" });
    } catch (error) {
      console.error("Error deleting rating:", error);
      res.status(500).json({ error: "删除评分失败" });
    }
  },
};
